package cn.stylefeng.guns.modular.tao.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.tao.api.AESCoder;
import cn.stylefeng.guns.modular.tao.api.ApiGetToken;
import cn.stylefeng.guns.modular.tao.api.Config;
import cn.stylefeng.guns.modular.tao.api.HttpRequest;
import cn.stylefeng.guns.modular.tao.entity.TaoStock;
import cn.stylefeng.guns.modular.tao.model.params.TaoStockParam;
import cn.stylefeng.guns.modular.tao.service.TaoStockService;
import cn.stylefeng.guns.sys.modular.tao.entity.Depository;
import cn.stylefeng.guns.sys.modular.tao.entity.Goods;
import cn.stylefeng.guns.sys.modular.tao.entity.Stock;
import cn.stylefeng.guns.sys.modular.tao.model.params.DepositoryParam;
import cn.stylefeng.guns.sys.modular.tao.model.params.GoodsParam;
import cn.stylefeng.guns.sys.modular.tao.model.params.GoodsSkusParam;
import cn.stylefeng.guns.sys.modular.tao.model.params.StockParam;
import cn.stylefeng.guns.sys.modular.tao.model.result.GoodsResult;
import cn.stylefeng.guns.sys.modular.tao.service.DepositoryService;
import cn.stylefeng.guns.sys.modular.tao.service.GoodsService;
import cn.stylefeng.guns.sys.modular.tao.service.GoodsSkusService;
import cn.stylefeng.guns.sys.modular.tao.service.StockService;
import cn.stylefeng.guns.sys.modular.tao.service.serviceImpl.GoodsServiceImpl;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 控制器
 *
 * @author zt
 * @Date 2019-07-09 11:07:06
 */
@Controller
@RequestMapping("/taoStock")
public class TaoStockController extends BaseController {

    private String PREFIX = "/stock/taoStock";
    @Autowired
    private TaoStockService taoStockService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsSkusService goodsSkusService;
    @Autowired
    private DepositoryService depositoryService;
    @Autowired
    private StockService stockService;

    /**
     * 跳转到主页面
     *
     * @author 陶启然
     * @Date 2019-07-09
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/taoStock.html";
    }

    /**
     * 新增页面
     *
     * @author 陶启然
     * @Date 2019-07-09
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/taoStock_add.html";
    }

    /**
     * 编辑页面
     *
     * @author 陶启然
     * @Date 2019-07-09
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/taoStock_edit.html";
    }

    /**
     * 新增接口
     *
     * @author 陶启然
     * @Date 2019-07-09
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(TaoStockParam taoStockParam) {
        this.taoStockService.add(taoStockParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author 陶启然
     * @Date 2019-07-09
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(TaoStockParam taoStockParam) {
        this.taoStockService.update(taoStockParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author 陶启然
     * @Date 2019-07-09
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(TaoStockParam taoStockParam) {
        this.taoStockService.delete(taoStockParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author 陶启然
     * @Date 2019-07-09
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(TaoStockParam taoStockParam) {
        TaoStock detail = this.taoStockService.getById(taoStockParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author 陶启然
     * @Date 2019-07-09
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(TaoStockParam taoStockParam) {
        return this.taoStockService.findPageBySpec(taoStockParam);
    }

    //    @Scheduled(cron = "0 0 5 * * ? *")


    /**
     * 从管家婆获取商品的信息和第一个价格
     */
    @RequestMapping("/getGoodsByGJBFirstPrice")
    @ResponseBody
    @ApiOperation(value = "从管家婆获取商品的信息和第一个价格", httpMethod = "POST", notes = "从管家婆获取商品的信息和第一个价格", tags = {"从管家婆获取商品的信息和第一个价格"})
    @ApiImplicitParams({
    })
    public void getGoodsByGJBFirstPrice(HttpServletResponse response) throws Exception {
        String timestamp = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1、通过Date类获取系统当前时间
        timestamp = df.format(new Date());
        //获取token
        ApiGetToken apiGetToken = new ApiGetToken();
        String token = apiGetToken.DoGetToken();
        //拼接sign
        String ret = "";
        //接口调用参数组装
        Map<String,String> param = new HashMap<>();
        //签名参数
        AESCoder coder = new AESCoder();
        param.put("appkey", Config.appkey);
        param.put("method", "zyx.selfbuiltmall.queryproductinfo");
        param.put("pagesize", "100");
        param.put("pageno", "1");
        // param.put("ptypeids","");
        //获取的价格类型
        param.put("pricetype", "1");
        param.put("timestamp", timestamp);
        param.put("token", token);
        param.put("sign", coder.SignRequest(param, Config.sign_key));
        //post报文
        String postString = "";
        for (String in : param.keySet()) {
            postString += in + "=" + URLEncoder.encode(param.get(in).toString(), "utf-8") + "&";
        }
        postString = postString.substring(0, postString.length() - 1);
        ret = HttpRequest.sendPost(Config.api_link, postString);
        JSONObject jsonObject = JSONObject.parseObject(ret);
        //获取总记录条数
        String totalresults = jsonObject.getJSONObject("response").getString("totalresults");
        Integer totalPage = Integer.parseInt(totalresults);
        totalPage = totalPage % 100 == 0 ? totalPage / 100 : (totalPage / 100) + 1;
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /*                             业务逻辑                                                             */
        System.out.println(ret);
        //循环访问接口获取值
        int a = 10;
        for (int i = 1; i <= totalPage; i++) {
            String timestamps = null;
            SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //1、通过Date类获取系统当前时间
            timestamps = dfs.format(new Date());
            //获取token
            ApiGetToken apiGetTokens = new ApiGetToken();
            String tokens = apiGetTokens.DoGetToken();
            //拼接sign
            String rets = "";
            //接口调用参数组装
            Map<String,String> params = new HashMap<>();
            //签名参数
            AESCoder coders = new AESCoder();
            params.put("appkey", Config.appkey);
            params.put("method", "zyx.selfbuiltmall.queryproductinfo");
            params.put("pagesize", "100");
            params.put("pageno", String.valueOf(i));
            // param.put("ptypeids","");
            //获取的价格类型
            params.put("pricetype", "1");
            params.put("timestamp", timestamps);
            params.put("token", tokens);
            params.put("sign", coders.SignRequest(params, Config.sign_key));
            //post报文
            String postStrings = "";
            for (String in : params.keySet()) {
                postStrings += in + "=" + URLEncoder.encode(params.get(in).toString(), "utf-8") + "&";
            }
            postStrings = postStrings.substring(0, postStrings.length() - 1);
            rets = HttpRequest.sendPost(Config.api_link, postStrings);
            JSONObject jsonObjects = JSONObject.parseObject(rets);

            JSONArray jsonArray = jsonObjects.getJSONObject("response").getJSONArray("ptypes");
            for (int j = 0; j < jsonArray.size(); j++) {
                GoodsParam goods = new GoodsParam();
                GoodsSkusParam goodsSkusParam = new GoodsSkusParam();
                JSONObject jsonObjectt = JSONObject.parseObject(jsonArray.get(j).toString());
                if (!jsonObjectt.getString("id").equals("") && jsonObjectt.getString("id") != null) {
                    goods.setUsercode(jsonObjectt.getString("usercode"));
                    goods.setBarcode(jsonObjectt.getString("barcode"));
                    goods.setFullname(jsonObjectt.getString("fullname"));
                    goods.setName(jsonObjectt.getString("name"));
                    goods.setType(jsonObjectt.getString("type"));
                    goods.setArea(jsonObjectt.getString("area"));
                    goods.setStandard(jsonObjectt.getString("standard"));
                    goods.setComment(jsonObjectt.getString("comment"));
                    goods.setId(Long.valueOf(jsonObjectt.getString("id")));
                    goods.setIsstop(jsonObjectt.getString("isstop"));
                    goods.setBrandname(jsonObjectt.getString("brandname"));
                    goods.setWeight(new BigDecimal(jsonObjectt.getString("weight")));
                    goods.setLengths(new BigDecimal(jsonObjectt.getString("length")));
                    goods.setWidth(new BigDecimal(jsonObjectt.getString("width")));
                    goods.setHeight(new BigDecimal(jsonObjectt.getString("height")));
                    goods.setPrice(new BigDecimal(jsonObjectt.getString("price")));
                    goods.setUpdateTime(new Date());
                    //默认上架
                    goods.setState(1);
                    goodsService.add(goods);
                    JSONObject skus = jsonObjectt.getJSONArray("skus").getJSONObject(0);
                    goodsSkusParam.setSkuid(Long.parseLong(skus.getString("skuid")));
                    goodsSkusParam.setPtypeid(Long.parseLong(skus.getString("ptypeid")));
                    goodsSkusParam.setSkucode(skus.getString("skucode"));
                    goodsSkusParam.setFullbarcode(skus.getString("fullbarcode"));
                    goodsSkusParam.setProp1(skus.getString("prop1"));
                    goodsSkusParam.setProp2(skus.getString("prop2"));
                    goodsSkusParam.setUnitname(skus.getString("unitname"));
                    goodsSkusParam.setUnitid(skus.getString("unitid"));
                    goodsSkusParam.setUcode(new BigDecimal(skus.getString("ucode")));
                    goodsSkusParam.setUrate(new BigDecimal(skus.getString("urate")));
                    goodsSkusParam.setProp1id(skus.getString("prop1id"));
                    goodsSkusParam.setProp2id(skus.getString("prop2id"));
                    goodsSkusService.add(goodsSkusParam);

                } else {
                    return;
                }

            }
        }
    }


    /**
     * 获取昨天至今天新增或者修改的数据  并且价格为第一个价格
     */
    @RequestMapping("/getGoodsByYesterdayOnePrice")
    @ResponseBody
    @ApiOperation(value = "获取昨天与今天修改或更新的商品第一个价格", httpMethod = "POST", notes = "获取昨天与今天修改或更新的商品", tags = {"测试4"})
    @ApiImplicitParams({
    })
    public ResponseData getGoodsByYesterday(HttpServletResponse response) throws Exception {
        String timestamp = null;
        String yesterday = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1、通过Date类获取系统当前时间
        timestamp = df.format(new Date());

        //获取昨天时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -1);
        Date time = calendar.getTime();
        yesterday = df.format(time);
        //获取token
        ApiGetToken apiGetToken = new ApiGetToken();
        String token = apiGetToken.DoGetToken();
        //拼接sign
        String ret = "";
        //接口调用参数组装
        Map<String, String> param = new HashMap<>();
        //签名参数
        AESCoder coder = new AESCoder();
        param.put("appkey", Config.appkey);
        param.put("method", "zyx.selfbuiltmall.queryproductinfo");
        param.put("pagesize", "100");
        param.put("pageno", "1");
        param.put("begintime", yesterday);
        param.put("endtime", timestamp);
        // param.put("ptypeids","");
        //获取的价格类型
        param.put("pricetype", "1");
        param.put("timestamp", timestamp);
        param.put("token", token);
        param.put("sign", coder.SignRequest(param, Config.sign_key));
        //post报文
        String postString = "";
        for (String in : param.keySet()) {
            postString += in + "=" + URLEncoder.encode(param.get(in).toString(), "utf-8") + "&";
        }
        postString = postString.substring(0, postString.length() - 1);
        ret = HttpRequest.sendPost(Config.api_link, postString);
        JSONObject jsonObject = JSONObject.parseObject(ret);
        //获取总记录条数
        String totalresults = jsonObject.getJSONObject("response").getString("totalresults");
        Integer totalPage = Integer.parseInt(totalresults);
        totalPage = totalPage % 100 == 0 ? totalPage / 100 : (totalPage / 100) + 1;
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //循环访问接口获取值
        int a = 10;
        for (int i = 1; i <= totalPage; i++) {
            String timestamps = null;
            String yesterdays = null;
            SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //1、通过Date类获取系统当前时间
            timestamps = dfs.format(new Date());
            //获取昨天时间
            Calendar calendars = Calendar.getInstance();
            calendars.setTime(new Date());
            calendars.add(calendars.DATE, -1);
            Date times = calendars.getTime();
            yesterdays = dfs.format(times);
            //获取token
            ApiGetToken apiGetTokens = new ApiGetToken();
            String tokens = apiGetTokens.DoGetToken();
            //拼接sign
            String rets = "";
            //接口调用参数组装
            Map<String,String> params = new HashMap<>();
            //签名参数
            AESCoder coders = new AESCoder();
            params.put("appkey", Config.appkey);
            params.put("method", "zyx.selfbuiltmall.queryproductinfo");
            params.put("pagesize", "100");
            params.put("pageno", String.valueOf(i));
            param.put("begintime", yesterdays);
            param.put("endtime", timestamps);
            // param.put("ptypeids","");
            //获取的价格类型
            params.put("pricetype", "1");
            params.put("timestamp", timestamps);
            params.put("token", tokens);
            params.put("sign", coders.SignRequest(params, Config.sign_key));
            //post报文
            String postStrings = "";
            for (String in : params.keySet()) {
                postStrings += in + "=" + URLEncoder.encode(params.get(in).toString(), "utf-8") + "&";
            }
            postStrings = postStrings.substring(0, postStrings.length() - 1);
            rets = HttpRequest.sendPost(Config.api_link, postStrings);
            JSONObject jsonObjects = JSONObject.parseObject(rets);

            JSONArray jsonArray = jsonObjects.getJSONObject("response").getJSONArray("ptypes");
            for (int j = 0; j < jsonArray.size(); j++) {
                GoodsParam goods = new GoodsParam();
                GoodsSkusParam goodsSkusParam = new GoodsSkusParam();
                JSONObject jsonObjectt = JSONObject.parseObject(jsonArray.get(j).toString());
                Goods id = goodsService.getById(jsonObjectt.getString("id"));
                if (!jsonObjectt.getString("id").equals("") && jsonObjectt.getString("id") != null) {
                    //如果id存在于数据库  就更新这条记录  否则就增加这条记录
                    if (id == null) {
                        goods.setUsercode(jsonObjectt.getString("usercode"));
                        goods.setBarcode(jsonObjectt.getString("barcode"));
                        goods.setFullname(jsonObjectt.getString("fullname"));
                        goods.setName(jsonObjectt.getString("name"));
                        goods.setType(jsonObjectt.getString("type"));
                        goods.setArea(jsonObjectt.getString("area"));
                        goods.setStandard(jsonObjectt.getString("standard"));
                        goods.setComment(jsonObjectt.getString("comment"));
                        goods.setId(Long.valueOf(jsonObjectt.getString("id")));
                        goods.setIsstop(jsonObjectt.getString("isstop"));
                        goods.setBrandname(jsonObjectt.getString("brandname"));
                        goods.setWeight(new BigDecimal(jsonObjectt.getString("weight")));
                        goods.setLengths(new BigDecimal(jsonObjectt.getString("length")));
                        goods.setWidth(new BigDecimal(jsonObjectt.getString("width")));
                        goods.setHeight(new BigDecimal(jsonObjectt.getString("height")));
                        goods.setPrice(new BigDecimal(jsonObjectt.getString("price")));
                        goods.setUpdateTime(new Date());
                        //默认上架
                        goods.setState(1);
                        goodsService.add(goods);
                        JSONObject skus = jsonObjectt.getJSONArray("skus").getJSONObject(0);
                        goodsSkusParam.setSkuid(Long.parseLong(skus.getString("skuid")));
                        goodsSkusParam.setPtypeid(Long.parseLong(skus.getString("ptypeid")));
                        goodsSkusParam.setSkucode(skus.getString("skucode"));
                        goodsSkusParam.setFullbarcode(skus.getString("fullbarcode"));
                        goodsSkusParam.setProp1(skus.getString("prop1"));
                        goodsSkusParam.setProp2(skus.getString("prop2"));
                        goodsSkusParam.setUnitname(skus.getString("unitname"));
                        goodsSkusParam.setUnitid(skus.getString("unitid"));
                        goodsSkusParam.setUcode(new BigDecimal(skus.getString("ucode")));
                        goodsSkusParam.setUrate(new BigDecimal(skus.getString("urate")));
                        goodsSkusParam.setProp1id(skus.getString("prop1id"));
                        goodsSkusParam.setProp2id(skus.getString("prop2id"));
                        goodsSkusService.add(goodsSkusParam);
                    } else if (id != null) {
                        goods.setUsercode(jsonObjectt.getString("usercode"));
                        goods.setBarcode(jsonObjectt.getString("barcode"));
                        goods.setFullname(jsonObjectt.getString("fullname"));
                        goods.setName(jsonObjectt.getString("name"));
                        goods.setType(jsonObjectt.getString("type"));
                        goods.setArea(jsonObjectt.getString("area"));
                        goods.setStandard(jsonObjectt.getString("standard"));
                        goods.setComment(jsonObjectt.getString("comment"));
                        goods.setId(Long.valueOf(jsonObjectt.getString("id")));
                        goods.setIsstop(jsonObjectt.getString("isstop"));
                        goods.setBrandname(jsonObjectt.getString("brandname"));
                        goods.setWeight(new BigDecimal(jsonObjectt.getString("weight")));
                        goods.setLengths(new BigDecimal(jsonObjectt.getString("length")));
                        goods.setWidth(new BigDecimal(jsonObjectt.getString("width")));
                        goods.setHeight(new BigDecimal(jsonObjectt.getString("height")));
                        goods.setPrice(new BigDecimal(jsonObjectt.getString("price")));
                        //默认上架
                        goods.setState(1);
                        goodsService.update(goods);
                        JSONObject skus = jsonObjectt.getJSONArray("skus").getJSONObject(0);
                        goodsSkusParam.setSkuid(Long.parseLong(skus.getString("skuid")));
                        goodsSkusParam.setPtypeid(Long.parseLong(skus.getString("ptypeid")));
                        goodsSkusParam.setSkucode(skus.getString("skucode"));
                        goodsSkusParam.setFullbarcode(skus.getString("fullbarcode"));
                        goodsSkusParam.setProp1(skus.getString("prop1"));
                        goodsSkusParam.setProp2(skus.getString("prop2"));
                        goodsSkusParam.setUnitname(skus.getString("unitname"));
                        goodsSkusParam.setUnitid(skus.getString("unitid"));
                        goodsSkusParam.setUcode(new BigDecimal(skus.getString("ucode")));
                        goodsSkusParam.setUrate(new BigDecimal(skus.getString("urate")));
                        goodsSkusParam.setProp1id(skus.getString("prop1id"));
                        goodsSkusParam.setProp2id(skus.getString("prop2id"));
                        goodsSkusService.update(goodsSkusParam);
                    }
                } else {
                    return ResponseData.success("同步成功");
                }
            }
        }
        return ResponseData.success("同步成功");
    }


    /**
     *
     */
    @RequestMapping("/uploadGoods")
    @ResponseBody
    public void test(HttpServletResponse response) throws Exception {

        List<GoodsResult> allGoods= goodsService.getAllGoodsAndSku();
        List<Map<String,Object>> rows = new ArrayList<Map<String,Object>>();

        for(GoodsResult goodsResult: allGoods){
            Map<String,Object> maps = new HashMap();
            maps.put("NumId",goodsResult.getId());
            maps.put("ProductName",goodsResult.getFullname());
            maps.put("OuterId",goodsResult.getSkuCode());
            maps.put("StockStatus",goodsResult.getState());
            rows.add(maps);
        }
        String timestamp = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1、通过Date类获取系统当前时间
        timestamp = df.format(new Date());
        //获取token
        ApiGetToken apiGetToken = new ApiGetToken();
        String token = apiGetToken.DoGetToken();
        //拼接sign
        String ret = "";
        //接口调用参数组装
        Map<String, String> param = new HashMap<>();
        //签名参数
        AESCoder coder = new AESCoder();
        param.put("appkey", Config.appkey);
        param.put("method", "zyx.selfbuiltmall.uploadproducts");
        param.put("timestamp", timestamp);
        param.put("shopkey",Config.shop_key);
        param.put("products", JSON.toJSONString(rows));
        param.put("token", token);
        param.put("sign", coder.SignRequest(param, Config.sign_key));
        //post报文
        String postString = "";
        for (String in : param.keySet()) {
            postString += in + "=" + URLEncoder.encode(param.get(in), "utf-8") + "&";
        }
        postString = postString.substring(0, postString.length() - 1);
        ret = HttpRequest.sendPost(Config.api_link, postString);
        JSONObject jsonObject = JSONObject.parseObject(ret);
        System.out.println(ret);
    }

    /**
         * 获取库存
         */
        @RequestMapping("/getInformation")
        @ResponseBody
        public ResponseData getInformation(HttpServletResponse response) throws Exception{
            //所有商品id
            List<String> allGoods= goodsService.getAllGoods2And();
            //每次100 条
            Map map = TaoStockController.groupList(allGoods);
            //获取所有的仓库地址  挨个查每个仓库的库存
            List<String> AllDepository =  depositoryService.getAllDepository();
            for(int i = 0;i<map.size();i++){
                for(int j=0;j<AllDepository.size();j++){
                    List<String> AllDepositorys = new ArrayList<>();
                    AllDepositorys.add(AllDepository.get(j));
                    String timestamp = null;
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //1、通过Date类获取系统当前时间
                    timestamp = df.format(new Date());
                    //获取token
                    ApiGetToken apiGetToken = new ApiGetToken();
                    String token = apiGetToken.DoGetToken();
                    //拼接sign
                    String ret = "";
                    //接口调用参数组装
                    Map<String, Object> param = new HashMap<>();
                    //签名参数
                    AESCoder coder = new AESCoder();
                    param.put("appkey", Config.appkey);
                    param.put("method", "zyx.selfbuiltmall.batchquerysaleqty");
                    param.put("timestamp", timestamp);
                    param.put("shopkey",Config.shop_key);
                    param.put("token", token);
                    param.put("ktypeids", AllDepositorys);
                    param.put("numids", map.get("keyName"+i));
                    param.put("sign", coder.SignRequests(param, Config.sign_key));
                    //post报文
                    String postString = "";
                    for (String in : param.keySet()) {
                        postString += in + "=" + URLEncoder.encode(param.get(in).toString(), "utf-8") + "&";
                    }
                    postString = postString.substring(0, postString.length() - 1);
                    ret = HttpRequest.sendPost(Config.api_link, postString);
                    JSONObject jsonObject = JSONObject.parseObject(ret);
                    System.out.println(jsonObject);
                    JSONArray jsonObject1 = jsonObject.getJSONObject("response").getJSONArray("data");
                    for(int z=0; z<jsonObject1.size(); z++){
                        StockParam stockParam = new StockParam();
                        JSONObject jsonObject2 = JSON.parseObject(jsonObject1.get(z).toString());
                        //如果该仓库有库存 就存入数据库中
                        if(new BigDecimal(jsonObject2.getString("saleqty")).compareTo(BigDecimal.ZERO)!=0){
                            //如果数据库中这个商品id存在 但是库存id不一致就添加
                            if( stockService.getByNumIdAndSku(jsonObject2.getString("numid"),AllDepository.get(i))==null){
                                stockParam.setNumId(jsonObject2.getString("numid"));
                                stockParam.setQty(new BigDecimal(jsonObject2.getString("qty")));
                                stockParam.setSaleqty(new BigDecimal(jsonObject2.getString("saleqty")));
                                stockParam.setKtypeId(AllDepository.get(i));
                                stockService.add(stockParam);
                            }else{
                                stockParam.setNumId(jsonObject2.getString("numid"));
                                stockParam.setQty(new BigDecimal(jsonObject2.getString("qty")));
                                stockParam.setSaleqty(new BigDecimal(jsonObject2.getString("saleqty")));
                                stockParam.setKtypeId(AllDepository.get(i));
                                stockService.updateByNumId(stockParam);
                            }
                        }
                    }

                }
            }
            return ResponseData.success();
        }






    /**
     * 获取库存
     */
    @RequestMapping("/getInformations")
    @ResponseBody
    public ResponseData getInformations(HttpServletResponse response) throws Exception{
        //所有商品id
        List<String> allGoods= goodsService.getAllGoods2And();
        //每次100 条
        Map map = TaoStockController.groupList(allGoods);
        //获取所有的仓库地址  挨个查每个仓库的库存
        List<String> AllDepository =  depositoryService.getAllDepository();
        for(int i = 0;i<map.size();i++) {
            /* for(int j=0;j<AllDepository.size();j++){*/
            List<String> AllDepositorys = new ArrayList<>();
            AllDepositorys.add(AllDepository.get(i));
            String timestamp = null;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //1、通过Date类获取系统当前时间
            timestamp = df.format(new Date());
            //获取token
            ApiGetToken apiGetToken = new ApiGetToken();
            String token = apiGetToken.DoGetToken();
            //拼接sign
            String ret = "";
            //接口调用参数组装
            Map<String, Object> param = new HashMap<>();
            //签名参数
            AESCoder coder = new AESCoder();
            param.put("appkey", Config.appkey);
            param.put("method", "zyx.selfbuiltmall.batchquerysaleqty");
            param.put("timestamp", timestamp);
            param.put("shopkey", Config.shop_key);
            param.put("token", token);
            param.put("ktypeids", AllDepositorys);
            param.put("numids", map.get("keyName" + i));
            param.put("sign", coder.SignRequests(param, Config.sign_key));
            //post报文
            String postString = "";
            for (String in : param.keySet()) {
                postString += in + "=" + URLEncoder.encode(param.get(in).toString(), "utf-8") + "&";
            }
            postString = postString.substring(0, postString.length() - 1);
            ret = HttpRequest.sendPost(Config.api_link, postString);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            System.out.println(jsonObject);
            JSONArray jsonObject1 = jsonObject.getJSONObject("response").getJSONArray("data");
              /*      for(int z=0; z<jsonObject1.size(); z++){
                        StockParam stockParam = new StockParam();
                        JSONObject jsonObject2 = JSON.parseObject(jsonObject1.get(z).toString());
                        //如果该仓库有库存 就存入数据库中
                        if(new BigDecimal(jsonObject2.getString("saleqty")).compareTo(BigDecimal.ZERO)==1){
                            if(stockService.getByNumId(jsonObject2.getString("numid"))==null){
                                stockParam.setNumId(jsonObject2.getString("numid"));
                                stockParam.setQty(new BigDecimal(jsonObject2.getString("qty")));
                                stockParam.setSaleqty(new BigDecimal(jsonObject2.getString("saleqty")));
                                stockParam.setKtypeId(AllDepository.get(i));
                                stockService.add(stockParam);
                            }else{
                                stockParam.setNumId(jsonObject2.getString("numid"));
                                stockParam.setQty(new BigDecimal(jsonObject2.getString("qty")));
                                stockParam.setSaleqty(new BigDecimal(jsonObject2.getString("saleqty")));
                                stockParam.setKtypeId(AllDepository.get(i));
                                stockService.updateByNumId(stockParam);
                            }
                        }
                    }*/

        /*}*/
        }
        return ResponseData.success();
    }

    public static Map groupList(List list){
        int listSize=list.size();
        int toIndex=100;
        Map map = new HashMap();     //用map存起来新的分组后数据
        int keyToken = 0;
        for(int i = 0;i<list.size();i+=100){
            if(i+100>listSize){        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                toIndex=listSize-i;
            }
            List newList = list.subList(i,i+toIndex);
            map.put("keyName"+keyToken, newList);
            keyToken++;
        }

        return map;
    }

    /**
         * 所有仓库获取
         */
        @RequestMapping("/getKTypeList")
        @ResponseBody
        public ResponseData getKTypeList(HttpServletResponse response) throws Exception {
            String timestamp = null;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //1、通过Date类获取系统当前时间
            timestamp = df.format(new Date());
            //获取token
            ApiGetToken apiGetToken = new ApiGetToken();
            String token = apiGetToken.DoGetToken();
            //拼接sign
            String ret = "";
            //接口调用参数组装
            Map<String, Object> param = new HashMap<>();
            //签名参数
            AESCoder coder = new AESCoder();
            param.put("appkey", Config.appkey);
            param.put("method", "zyx.selfbuiltmall.queryktypelist");
            param.put("timestamp", timestamp);
            param.put("shopkey",Config.shop_key);
            param.put("token", token);
            param.put("pagesize",100);
            param.put("pageno",2);
            param.put("sign", coder.SignRequests(param, Config.sign_key));
            //post报文
            String postString = "";
            for (String in : param.keySet()) {
                postString += in + "=" + URLEncoder.encode(param.get(in).toString(), "utf-8") + "&";
            }
            postString = postString.substring(0, postString.length() - 1);
            ret = HttpRequest.sendPost(Config.api_link, postString);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            String totalresults = jsonObject.getJSONObject("response").getString("totalresults");
            Integer totalPage = Integer.parseInt(totalresults);
            totalPage = totalPage % 100 == 0 ? totalPage / 100 : (totalPage / 100) + 1;
            ///////////////////////////////////////////////////////////////////////////////////////
            /*                             业务逻辑                                                             */
            for(int i =1 ;i<=totalPage;i++){
                String timestamps = null;
                SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //1、通过Date类获取系统当前时间
                timestamps = dfs.format(new Date());
                //获取token
                ApiGetToken apiGetTokens = new ApiGetToken();
                String tokens = apiGetTokens.DoGetToken();
                //拼接sign
                String rets = "";
                //接口调用参数组装
                Map<String, Object> params = new HashMap<>();
                //签名参数
                AESCoder coders = new AESCoder();
                params.put("appkey", Config.appkey);
                params.put("method", "zyx.selfbuiltmall.queryktypelist");
                params.put("timestamp", timestamps);
                params.put("shopkey",Config.shop_key);
                params.put("token", tokens);
                params.put("pagesize",100);
                params.put("pageno",String.valueOf(i));
                params.put("sign", coders.SignRequests(params, Config.sign_key));
                //post报文
                String postStrings = "";
                for (String in : params.keySet()) {
                    postStrings += in + "=" + URLEncoder.encode(params.get(in).toString(), "utf-8") + "&";
                }
                postStrings = postStrings.substring(0, postStrings.length() - 1);
                rets = HttpRequest.sendPost(Config.api_link, postStrings);
                JSONObject jsonObjects = JSONObject.parseObject(rets);
                //存入数据库
                JSONArray jsonArray = jsonObjects.getJSONObject("response").getJSONArray("ktypelist");
                for(int j =0 ; j<jsonArray.size();j++){
                    JSONObject jsonObjectt = JSONObject.parseObject(jsonArray.get(j).toString());
                    DepositoryParam depository = new DepositoryParam();
                    //存在就更新  否则就添加
                    System.out.println(jsonObjectt.getString("ktypeid"));
                    DepositoryParam ktypeid = depositoryService.getByKtypeId(jsonObjectt.getString("ktypeid"));
                    if(ktypeid!=null){
                        depository.setKtypeId(jsonObjectt.getString("ktypeid"));
                        depository.setFullName(jsonObjectt.getString("fullname"));
                        depository.setUserCode(jsonObjectt.getString("usercode"));
                        depository.setName(jsonObjectt.getString("name"));
                        depository.setNamePy(jsonObjectt.getString("namepy"));
                        depository.setProvince(jsonObjectt.getString("province"));
                        depository.setCity(jsonObjectt.getString("city"));
                        depository.setSection(jsonObjectt.getString("section"));
                        depository.setAddress(jsonObjectt.getString("address"));
                        depository.setZip(jsonObjectt.getString("zip"));
                        depository.setContactor(jsonObjectt.getString("contactor"));
                        depository.setPhone(jsonObjectt.getString("phone"));
                        depository.setIsStop(jsonObjectt.getString("isstop"));
                        depository.setComment(jsonObjectt.getString("comment"));
                        depository.setSendType(Integer.parseInt(jsonObjectt.getString("sendtype")));
                        depositoryService.updateByKtypeId(depository);
                    }else{
                        System.out.println(jsonObjectt);
                        depository.setKtypeId(jsonObjectt.getString("ktypeid"));
                        depository.setFullName(jsonObjectt.getString("fullname"));
                        depository.setUserCode(jsonObjectt.getString("usercode"));
                        depository.setName(jsonObjectt.getString("name"));
                        depository.setNamePy(jsonObjectt.getString("namepy"));
                        depository.setProvince(jsonObjectt.getString("province"));
                        depository.setCity(jsonObjectt.getString("city"));
                        depository.setSection(jsonObjectt.getString("section"));
                        depository.setAddress(jsonObjectt.getString("address"));
                        depository.setZip(jsonObjectt.getString("zip"));
                        depository.setContactor(jsonObjectt.getString("contactor"));
                        depository.setPhone(jsonObjectt.getString("phone"));
                        depository.setIsStop(jsonObjectt.getString("isstop"));
                        depository.setComment(jsonObjectt.getString("comment"));
                        depository.setSendType(Integer.parseInt(jsonObjectt.getString("sendtype")));
                        depositoryService.add(depository);
                    }

                }
            }
            return ResponseData.success();
        }
}


